<template>
  <div class="amap-page-container">
    <!-- 地图部分 -->
    <!-- <el-amap ref="map" vid="container" :amap-manager="amapManager" :center="center" :zoom="zoom" :plugin="plugin" :events="events" class="amap-demo">
    </el-amap>-->
    <div id="container"></div>
    <!-- 菜单栏部分 -->
    <div class="menu menuStyle">
      <div class="func" :class="showComponent?'chooseFun': ''">
        <div class="avator">
          <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" :size="54"></el-avatar>
        </div>
        <div
          class="fun"
          v-for="items in roleFuns.slice(0, 3)"
          :key="items.functionId"
          @click="chooseFunA(items.component)"
        >
          <span class="iconfont" :class="items.iconFont"></span>
          <span class="funName">{{ items.name }}</span>
          <span class="choosed" v-if="showComponent == items.component"></span>
        </div>
        <div class="fun" @click="clearMarkerPoint">
          <span class="iconfont iconkefuzhongxin specicon"></span>
          <span class="funName">客服中心</span>
        </div>
        <div class="logoff" @click="toLogoff">注 销</div>
      </div>
      <!-- <keep-alive include=""> -->
      <component
        :is="showComponent"
        :funArray="funArray"
        :PersomMarketPoint="marketPoint"
        @getMain="getMainDate"
        @getPersonPoint="changePersonPoint"
        @getPersonTrack="getPersonTrack"
      ></component>
      <!-- </keep-alive> -->
    </div>
  </div>
</template>

<script>

import ConfigServerMain from 'components/configServers/ConfigServerMain'
import MonitoringCenterMain from 'components/monitoringCenter/MonitoringCenterMain'
import DataCenterMain from 'components/DataCenter/DataCenterMain'
import { chgStrToDate, dateFormat } from '@/base/utils'
import Storage from '@/base/storage.js'

export default {
  components: { ConfigServerMain, MonitoringCenterMain, DataCenterMain },
  data () {
    return {
      zoom: 13,
      center: [116.397428, 39.90923],
      showComponent: "", //当前显示组件名称
      funArray: [],
      map: '',
      lineArr: [[116.478935, 39.997761], [116.478939, 39.997825], [116.478912, 39.998549], [116.478912, 39.998549], [116.478998, 39.998555], [116.478998, 39.998555], [116.479282, 39.99856], [116.479658, 39.998528], [116.480151, 39.998453], [116.480784, 39.998302], [116.480784, 39.998302], [116.481149, 39.998184], [116.481573, 39.997997], [116.481863, 39.997846], [116.482072, 39.997718], [116.482362, 39.997718], [116.483633, 39.998935], [116.48367, 39.998968], [116.484648, 39.999861]],
      marker: '',//轨迹
      markerPoint: [[116.478935, 39.997761], [116.478939, 39.997825], [116.478912, 39.998549], [116.478912, 39.998549], [116.478998, 39.998555], [116.478998, 39.998555], [116.479282, 39.99856], [116.479658, 39.998528], [116.480151, 39.998453], [116.480784, 39.998302], [116.480784, 39.998302], [116.481149, 39.998184], [116.481573, 39.997997], [116.481863, 39.997846], [116.482072, 39.997718], [116.482362, 39.997718], [116.483633, 39.998935], [116.48367, 39.998968], [116.484648, 39.999861]],//人员点位
      markers: [],
      polyline: '',//还未经过的路线
      passedPolyline: '',//经过的轨迹
      roleFuns: '',//功能权限
      mouseTool: "",//右侧工具栏
      velocity: 500,
    };
  },
  computed: {

  },
  methods: {
    getMap () {
      // amap vue component
      console.log(amapManager._componentMap);
      // gaode map instance
      console.log(amapManager._map);
    },
    chooseFunA (componentName) {
      this.showComponent = componentName;
      if (componentName == 'ConfigServerMain') {
        let funArr = this.roleFuns.find(items => {
          return items.component == 'ConfigServerMain';
        })
        this.funArray = funArr.funs;
      } else if (componentName == 'DataCenterMain') {
        let funArr = this.roleFuns.find(items => {
          return items.component == 'DataCenterMain';
        })
        this.funArray = funArr.funs;
      }
    },
    getMainDate (data) {
      console.log(data);
    },
    //初始化地图
    initMap () {
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        center: this.center,
        zoom: this.zoom
      });
    },
    //初始化图标
    initMarker () {
      this.marker = new AMap.Marker({
        map: this.map,
        position: this.lineArr[0],
        icon: new AMap.Icon({
          image: "https://webapi.amap.com/images/car.png",
          // size: new AMap.Size(20, 20),  //图标大小
          // imageSize: new AMap.Size(20,20)
        }),
        offset: new AMap.Pixel(-20, -13), //调整图片偏移
        autoRotation: true, //自动旋转
        angle: -90 //图片旋转角度
      });
    },
    //初始化轨迹
    initroad () {
      //绘制还未经过的路线
      this.polyline = new AMap.Polyline({
        map: this.map,
        path: this.lineArr,
        showDir: true,
        strokeColor: "#28F", //线颜色--蓝色
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });
      //绘制路过了的轨迹
      this.passedPolyline = new AMap.Polyline({
        map: this.map,
        strokeColor: "#AF5", //线颜色-绿色
        //path: this.lineArr,
        // strokeOpacity: 1,     //线透明度
        strokeWeight: 6 //线宽
        // strokeStyle: "solid"  //线样式
      });
      this.marker.on("moving", e => {
        this.passedPolyline.setPath(e.passedPath);
      });
      this.map.setFitView(); //合适的视口
    },
    //绘制运动轨迹
    startAnimation () {
      this.showComponent = '';
      this.marker.moveAlong(this.lineArr, this.velocity);
    },
    //获取人员点位
    getPersonLocation () {
      this.showComponent = '';
      let _this = this;
      for (let i = 0, marker; i < this.markerPoint.length; i++) {
        marker = new AMap.Marker({
          map: this.map,
          icon: new AMap.Icon({
            image: "static/img/user.png",
            size: new AMap.Size(20, 20),  //图标大小
            imageSize: new AMap.Size(20, 20)
          }),
          position: this.markerPoint[i].pointer
        });
        // 设置label标签
        // label默认蓝框白底左上角显示，样式className为：amap-marker-label
        marker.setLabel({
          offset: new AMap.Pixel(0, -10),  //设置文本标注偏移量
          content: `<div class='usersPoint'>
                                <div class='num nums'>${_this.markerPoint[i].msisdn}</div>
                            </div>`, //设置文本标注内容
          direction: 'top', //设置文本标注方位
        });
        let flag = false;
        let content = '';
        //点标注的点击事件
        marker.on('click', function (e) {
          console.log(e);
          flag = !flag;
          if (flag) {
            content = `<div class='usersPoint'>
                                <div class='num'>${_this.markerPoint[i].msisdn}</div>
                                <div class="getPersonPointMsg">
                                    <div class='title'>定位时间</div>
                                    <div class='content'>${dateFormat(chgStrToDate(_this.markerPoint[i].time, true), "yyyy-MM-dd hh:mm:ss")}</div>
                                </div>
                                <div class="getPersonPointMsg">
                                    <div class='title'>定位地点</div>
                                    <div class='content'>${_this.markerPoint[i].inverseGeocoding}</div>
                                </div>
                            </div>`
          } else {
            content = `<div class='usersPoint'>
                                    <div class='num nums'>${_this.markerPoint[i].msisdn}</div>
                                </div>`
          }
          marker.setTop({ isTop: true });
          marker.setLabel({
            content: content,
          });
          console.log(e);
        });
        this.markers.push(marker);
      }
    },
    //清除人员点位和轨迹信息
    clearMarkerPoint () {
      this.map.remove(this.markers);
      this.map.remove(this.marker);
      if (this.polyline) {
        this.map.remove(this.polyline);
      }
      if (this.passedPolyline) {
        this.map.remove(this.passedPolyline);
      }
    },
    //获取用户所在城市信息
    showCityInfo () {
      //实例化城市查询类
      let citysearch = new AMap.CitySearch();
      let _this = this;
      //自动获取用户IP，返回当前城市
      citysearch.getLocalCity(function (status, result) {
        console.log(result);
        if (status === 'complete' && result.info === 'OK') {
          if (result && result.city && result.bounds) {
            // var cityinfo = result.city;
            let citybounds = result.bounds;
            // document.getElementById('tip').innerHTML = '您当前所在城市：'+cityinfo;
            //地图显示当前城市
            _this.map.setBounds(citybounds);
          }
        }
      });
    },
    //绘制人员点位
    changePersonPoint (data) {
      this.markerPoint = data;
      this.clearMarkerPoint();
      // this.map.setCenter(this.markerPoint[0]);
      this.getPersonLocation();
      this.map.setFitView();
    },
    //格式化时间轨迹回放日期选择
    formatTooltip (val) {
      return val + '点';
    },
    //绘制人员轨迹
    getPersonTrack (data, velocityRadio) {
      this.velocity = velocityRadio * 500;
      console.log(this.velocity);
      this.lineArr = data;
      this.clearMarkerPoint();
      this.initMarker();
      this.initroad();
      this.startAnimation();
    },
    //注销
    toLogoff () {
      this.$confirm('确定退出登陆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = '/lbs/usercenter/login/h5LoginOut';
        let params = {
          token: Storage.session.get('token')
        }
        this.$http.post(url, params).then(res => {
          let { retCode, retMsg, data } = res.data;
          if (retCode == '0') {//成功的情况
            this.$message({
              message: "注销成功",
              type: 'success'
            });
            sessionStorage.clear();
            this.$router.push('/login');
          } else {
            this.$alert(retMsg || '请求失败');
          }
        }).catch(err => {
          this.$alert(err)
        })
      }).catch(() => {

      });
    },
    //自定义围栏
    customRail () {
      this.overlays = [];
      this.mouseTool = new AMap.MouseTool(this.map);
      this.mouseTool.on('draw', (e) => {
        this.overlays.push(e.obj);
        console.log(e.obj);
      })
    },
    //绘制围栏
    draw (type) {
      switch (type) {
        case 'marker': {
          this.mouseTool.marker({
            //同Marker的Option设置
          });
          break;
        }
        case 'polyline': {
          this.mouseTool.polyline({
            strokeColor: '#80d8ff'
            //同Polyline的Option设置
          });
          break;
        }
        case 'polygon': {
          this.mouseTool.polygon({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'rectangle': {
          this.mouseTool.rectangle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Polygon的Option设置
          });
          break;
        }
        case 'circle': {
          this.mouseTool.circle({
            fillColor: '#00b0ff',
            strokeColor: '#80d8ff'
            //同Circle的Option设置
          });
          break;
        }
        case 'move': {
          this.mouseTool.close(false)
        }
        case 'remove': {
          this.mouseTool.close(true)
        }
      }
    },
  },
  created () {
    //this.showCityInfo();
    this.roleFuns = Storage.session.get('funArr');
    console.log(this.roleFuns);
  },
  mounted () {
    setTimeout(() => {
      this.initMap();
      this.showCityInfo();
      this.customRail();
    }, 400);
  }
}
</script>
<style lang='less' scoped>
//@import url(); 引入公共css类
.amap-page-container {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
#container {
  height: 100%;
  width: 100%;
}
.toolbar {
  position: absolute;
  top: 100px;
  left: 100px;
  width: 100px;
  height: 40px;
  z-index: 99;
}
.menu {
  display: flex;
  position: absolute;
  top: 10px;
  left: 15px;
  background-color: #fff;
  border-radius: 16px;
  opacity: 0.98;
  box-shadow: 4px 4px 7px 0px rgba(133, 133, 133, 0.17);
  .func {
    width: 85px;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 16px;
    background-color: #f9f9f9;
    border-right: 1px solid #e8e8e8;
  }
  .chooseFun {
    border-radius: 16px 0 0 16px;
  }
  .levelA {
    flex: 1;
    .user {
      height: 70px;
      background-color: #f9f9f9;
      border-radius: 0 16px 0 0;
    }
  }
  .logoff {
    position: absolute;
    bottom: 10px;
    font-size: 14px;
    color: grey;
    cursor: pointer;
  }
}
@media screen and (max-height: 822px) {
  .menuStyle {
    bottom: 30px;
  }
}
@media screen and (min-height: 823px) and (max-height: 900px) {
  .menuStyle {
    height: 800px;
  }
}
@media screen and (min-height: 901px) {
  .menuStyle {
    height: 900px;
  }
}
.avator {
  width: 55px;
  height: 55px;
  border-radius: 50%;
  border: 1px solid #333;
  margin: 20px 0;
}
.fun {
  width: 100%;
  height: 60px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 30px;
  position: relative;
  cursor: pointer;
  .funName {
    color: #454545;
    font-size: 13px;
  }
  .iconfont {
    font-size: 36px;
    color: #007aff;
  }
  .specicon {
    font-size: 30px;
    margin-bottom: 2px;
  }
  .choosed {
    display: inline-block;
    width: 5px;
    height: 35px;
    background-color: #007aff;
    position: absolute;
    left: 0;
  }
}
</style>
<style lang="less">
.amap-marker-label {
  border: 0;
  border-radius: 16px;
  background: #ffffff;
  box-shadow: 0px 11px 4px 0px rgba(0, 0, 0, 0.11);
}
.usersPoint {
  margin: 0 10px;
  .num {
    width: 100%;
    height: 26px;
    line-height: 26px;
    border-bottom: 1px solid #ebebeb;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #464646;
  }
  .nums {
    border: 0;
  }
  .getPersonPointMsg {
    margin: 5px 0;
    font-size: 12px;
    font-weight: 500;
    .title {
      height: 17px;
      font-family: PingFangSC-Medium, PingFang SC;
      color: #464646;
      line-height: 17px;
    }
    .content {
      height: auto;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #686666;
      line-height: 17px;
      width: 200px;
      white-space: normal;
    }
  }
}
.el-slider__bar {
  background-color: #808080;
}
</style>
